package com.github.wxiaoqi.security.biz.biz;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.biz.entity.BhFunction;
import com.github.wxiaoqi.security.biz.entity.BhIndustry;
import com.github.wxiaoqi.security.biz.entity.BhTask;
import com.github.wxiaoqi.security.biz.entity.BhTaskTag;
import com.github.wxiaoqi.security.biz.entity.BhTaskUserResume;
import com.github.wxiaoqi.security.biz.mapper.BhFunctionMapper;
import com.github.wxiaoqi.security.biz.mapper.BhIndustryMapper;
import com.github.wxiaoqi.security.biz.mapper.BhLableMapper;
import com.github.wxiaoqi.security.biz.mapper.BhTaskMapper;
import com.github.wxiaoqi.security.biz.mapper.BhTaskTagMapper;
import com.github.wxiaoqi.security.biz.mapper.BhTaskUserResumeMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.common.util.Query;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 任务表   存储发布的任务
 *
 * @author Mr.AG
 * @email 463540703@qq.com
 * @date 2018-05-16 10:29:08
 */
@Slf4j
@Service
public class BhTaskBiz extends BaseBiz<BhTaskMapper,BhTask> {
	
	@Autowired
	private BhFunctionMapper bhFunctionMapper;
	@Autowired
	private BhIndustryMapper bhIndustryMapper;
	@Autowired
	private BhTaskUserResumeMapper bhTaskUserResumeMapper;
	@Autowired
	private BhTaskTagMapper bhTaskTagMapper;
	@Autowired
	private BhLableMapper bhLableMapper;
	//进行中的任务
	public Integer queryRuningTask(Map<String, Object> req){
		String merNo = (String) req.get("merNo");
		//String attentionIndustry = (String) req.get("attentionIndustry");
        Example example = new Example(BhTask.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merNo", merNo);
        criteria.andEqualTo("taskStatus", "4");
        List<BhTask> list = mapper.selectByExample(example);
        return list.size();
	}
	//任务查询分页
	public TableResultResponse<BhTask> queryTaskPage(Map<String, Object> req) throws Exception{
		 log.info("任务查询分页biz - BhTaskBiz - queryTaskPage 传入参数{}", req);
		 String page = (String) req.get("page");
		 String limit = (String) req.get("limit");
		 String companyIndustry = (String) req.get("companyIndustry");
		 String companyFunction = (String) req.get("companyFunction");
		 String address = (String) req.get("address");
		 Example example = new Example(BhTask.class);
		 Criteria criteria = example.createCriteria();
		 //companyIndustry 行业
		 if(null != companyIndustry && !"".equals(companyIndustry)){
			 criteria.andEqualTo("companyIndustry", companyIndustry);
		 }
		 //companyFunction 职能
		 if(null != companyFunction && !"".equals(companyFunction)){
			 criteria.andEqualTo("companyFunction", companyFunction);
		 }
		 //address
		 if(null != address && !"".equals(address)){
			 criteria.andLike("address", "%"+address+"%");
		 }
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("page", page);
		 params.put("limit", limit);
		 Query query = new Query(params);
		 Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
		 //List<MarActivity> list = activityBiz.queryActivityList(params);
		 List<BhTask> taskList = mapper.selectByExample(example);
		 log.info("任务查询分页biz - BhTaskBiz - queryTaskPage   taskList{}", taskList.toArray());
		 for (BhTask bhTask : taskList) {
			//行业名
			 BhFunction function = bhFunctionMapper.selectByPrimaryKey(bhTask.getCompanyFunction());
			 bhTask.setCompanyFunctionName(function.getName());
			 //职能名
			 BhIndustry industry = bhIndustryMapper.selectByPrimaryKey(bhTask.getCompanyIndustry());
			 if(industry != null){
				 bhTask.setCompanyIndustryName(industry.getName());
			 }
			 //已投简历数
			 BhTaskUserResume  resume = new BhTaskUserResume();
			 if(resume != null){
				 resume.setTaskId(bhTask.getId());
			 }
			 int count = bhTaskUserResumeMapper.selectCount(resume);
			 bhTask.setCount(String.valueOf(count));
		}
		 log.info("任务查询分页biz - BhTaskBiz - queryTaskPage   参数补充后taskList{}", taskList.toArray());
		 return new TableResultResponse<BhTask>(result.getTotal(), taskList);
		 
	}
	//直接发布
	public Map<String, Object> directublish(Map<String, Object> reqs) {
		log.info("直接发布biz - BhTaskBiz - directublish {}", reqs);
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> req = new HashMap<String, Object>();
		req.putAll(reqs);
		try {
			//代码中添加id，freezeMoney，taskStatus，createtime
			String startTimes = (String) req.get("startTimes");
			String endTimes = (String) req.get("endTimes");
			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
			if(endTimes != null && !"".equals(endTimes)){
				req.remove("endTimes");
				req.put("endTime", format1.parse(endTimes));
			}
			
			BhTask task = EntityUtils.map2Bean(req, BhTask.class);
			String seqNo = String.valueOf(SnowFlake.getId());
			task.setId(seqNo);
			task.setTaskStatus("4");//进行中
			BigDecimal rewoard = task.getReward();
			//EntityUtils2.
			BigDecimal free = rewoard.multiply(new BigDecimal(task.getAmount()));
			task.setFreezeMoney(free);
			task.setCreatetime(new Date());
			task.setStartTime(new Date());
			mapper.insert(task);
			log.info("直接发布biz - BhTaskBiz - directublish task {}", EntityUtils.beanToMap(task));
			//lable
			String lables = task.getLable();
			if(lables != null && !"".equals(lables)){
				String[] tags = lables.split(",");
				for (int i = 0; i < tags.length; i++) {
					BhTaskTag btt = new BhTaskTag();
					btt.setCreatetime(new Timestamp(new Date().getTime()));
					btt.setTagId(tags[i]);
					btt.setTaskId(seqNo);
					bhTaskTagMapper.insert(btt);
					//更新权重
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", tags[i]);
					bhLableMapper.updateWeightById(map);
				}
			}
			result.put("code", ResponseCode.OK.getCode());
			result.put("msg", ResponseCode.OK.getMessage());
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			result.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
			result.put("success", false);
		}
		log.info("直接发布biz - BhTaskBiz - directublish 结束 {}", result);
		return result;
	}
	//编辑后发布
	public Map<String, Object> editpublish(Map<String, Object> reqs) {
		log.info("编辑后发布biz - BhTaskBiz - editpublish {}", reqs);
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> req = new HashMap<String, Object>();
		req.putAll(reqs);
		String taskId = (String) req.get("id");
		try {
			//代码中添加id，freezeMoney，taskStatus，createtime
			String startTimes = (String) req.get("startTimes");
			String endTimes = (String) req.get("endTimes");
			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
			if(endTimes != null && !"".equals(endTimes)){
				req.remove("endTimes");
				req.put("endTime", format1.parse(endTimes));
			}
			
			BhTask task = EntityUtils.map2Bean(req, BhTask.class);
			//String seqNo = sequenceNoService.getTaskNo();
			//task.setId(seqNo);
			task.setTaskStatus("4");//进行中
			BigDecimal rewoard = task.getReward();
			//EntityUtils2.
			BigDecimal free = rewoard.multiply(new BigDecimal(task.getAmount()));
			task.setFreezeMoney(free);
			task.setStartTime(new Date());
			mapper.updateByPrimaryKey(task);
			log.info("编辑后发布biz - BhTaskBiz - editpublish task {}", EntityUtils.beanToMap(task));
			//lable
			//清除该任务下全部标签，然后重新写入
			Example example = new Example(BhTaskTag.class);
		    Criteria criteria = example.createCriteria();
		    criteria.andEqualTo("taskId", taskId);
			bhTaskTagMapper.deleteByExample(example);
			String lables = task.getLable();
			if(lables != null && !"".equals(lables)){
				String[] tags = lables.split(",");
				for (int i = 0; i < tags.length; i++) {
					BhTaskTag btt = new BhTaskTag();
					btt.setCreatetime(new Timestamp(new Date().getTime()));
					btt.setTagId(tags[i]);
					btt.setTaskId(taskId);
					bhTaskTagMapper.insert(btt);
					//更新权重 -- 此处有bug，编辑的时候权重会重复增加
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", tags[i]);
					bhLableMapper.updateWeightById(map);
				}
			}
			result.put("code", ResponseCode.OK.getCode());
			result.put("msg", ResponseCode.OK.getMessage());
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			result.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
			result.put("success", false);
		}
		log.info("编辑后发布biz - BhTaskBiz - editpublish 结束 {}", result);
		return result;
	}
	/*
	 * 保存或者编辑不发布
	 */
	public Map<String, Object> saveOrEditTask(Map<String, Object> reqs) {
		log.info("不发布biz - BhTaskBiz  - saveOrEditTask 传入参数{}", reqs);
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> req = new HashMap<String, Object>();
		req.putAll(reqs);
		String id = (String) req.get("id");
		log.info("不发布biz - BhTaskBiz  - saveOrEditTask id{}", id);
		try {
			//代码中添加id，freezeMoney，taskStatus，createtime
			String startTimes = (String) req.get("startTimes");
			String endTimes = (String) req.get("endTimes");
			DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
			if(endTimes != null && !"".equals(endTimes)){
				req.remove("endTimes");
				req.put("endTime", format1.parse(endTimes));
			}
			
			BhTask task = EntityUtils.map2Bean(req, BhTask.class);

			task.setTaskStatus("5");
			BigDecimal rewoard = task.getReward();
			//EntityUtils2.
			BigDecimal free = rewoard.multiply(new BigDecimal(task.getAmount()));
			task.setFreezeMoney(free);
			if(null != id && !"".equals(id)){
				log.info("不发布biz - BhTaskBiz  - saveOrEditTask id != null");
				
			}else {
				log.info("不发布biz - BhTaskBiz  - saveOrEditTask id == null");
				task.setCreatetime(new Date());
				String seqNo = String.valueOf(SnowFlake.getId());
				id = seqNo;
				task.setId(seqNo);
			}
			
			mapper.insert(task);
			//lable
			if(null != id && !"".equals(id)){
				//清除该任务下全部标签，然后重新写入
				log.info("不发布biz - BhTaskBiz  - saveOrEditTask id != null2");
				Example example = new Example(BhTaskTag.class);
			    Criteria criteria = example.createCriteria();
			    criteria.andEqualTo("taskId", id);
				bhTaskTagMapper.deleteByExample(example);
			}else {
				log.info("不发布biz - BhTaskBiz  - saveOrEditTask id == null2");
			}
			String lables = task.getLable();
			if(lables != null && !"".equals(lables)){
				String[] tags = lables.split(",");
				for (int i = 0; i < tags.length; i++) {
					BhTaskTag btt = new BhTaskTag();
					btt.setCreatetime(new Timestamp(new Date().getTime()));
					btt.setTagId(tags[i]);
					btt.setTaskId(id);
					bhTaskTagMapper.insert(btt);
					//更新权重
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", tags[i]);
					bhLableMapper.updateWeightById(map);
				}
			}
			result.put("code", ResponseCode.OK.getCode());
			result.put("msg", ResponseCode.OK.getMessage());
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseCode.ABNORMAL_FIELDS.getCode());
			result.put("msg", ResponseCode.ABNORMAL_FIELDS.getMessage());
			result.put("success", false);
		}
		log.info("不发布biz - BhTaskBiz  - saveOrEditTask 结束{}", result);
		return result;
		
	}
	
}